package com.tango.webrtc_embedeed_demo

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.ConsoleMessage
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks

class MainActivity : Activity(), PermissionCallbacks {

    private val PERMISSION_REQUEST_CODE: Int = 100

    private lateinit var webView: WebView

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
        webView = findViewById(R.id.web_view)
        requestPermission()
    }

    @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
    fun init() {
        webView.webChromeClient = object : WebChromeClient() {
            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
//                logd("[web] ${consoleMessage?.message()}") //内含对象时，会导致崩溃
                return super.onConsoleMessage(consoleMessage)
            }

            override fun onPermissionRequest(request: PermissionRequest?) {
                //** 加入下面代码，才能授权读取摄像头和麦克风，使正常工作 **
                request?.grant(request.resources)
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    Toast.makeText(
                        this@MainActivity,
                        "join the room completed...",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
        //
        webView.settings.javaScriptEnabled = true
        webView.settings.mediaPlaybackRequiresUserGesture = false
        // 允许 WebRTC 的视频和音频捕获
        webView.settings.allowFileAccess = true
        webView.settings.allowContentAccess = true
        // 启用 DOM 存储和 WebRTC
        webView.settings.domStorageEnabled = true
        webView.settings.javaScriptCanOpenWindowsAutomatically = true
        //
        webView.settings.setSupportZoom(true)
        webView.addJavascriptInterface(this, "Android")
    }

    fun onJoinClick(v: View) {
        val inTheRoom = webView.visibility == View.VISIBLE
        if (inTheRoom) {
            webView.visibility = View.GONE
            webView.loadUrl("about:blank")
            (v as Button).text = "Join"
        } else {
            val roomNumber = findViewById<EditText>(R.id.et_room_number).text.toString()
            val displayName = findViewById<EditText>(R.id.et_diplay_name).text.toString()
            if (roomNumber.isEmpty() || displayName.isEmpty()) {
                Toast.makeText(
                    this,
                    "RoomNumber or DisplayName cannot be null...",
                    Toast.LENGTH_SHORT
                ).show()
                return
            }

            webView.visibility = View.VISIBLE
            val webrtcServer = "https://webrtc.lssvc.cn"
            val videoServer = "dev.lssvc.cn"
            val url =
                "${webrtcServer}/product/mobile/index.html?host=${videoServer}&roomKey=${roomNumber}&displayName=${displayName}&autoJoin=1"
            webView.loadUrl(url)
            (v as Button).text = "Leave"
        }
    }

    private fun requestPermission(): Boolean {
        val mPermissionList: Array<String> = run {
            if (Build.VERSION.SDK_INT >= 33) {
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.POST_NOTIFICATIONS
                )
            } else {
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO
                )
            }
        }

        if (EasyPermissions.hasPermissions(this, *mPermissionList)) {
            init()
            return true
        } else {
            EasyPermissions.requestPermissions(
                this,
                "",
                PERMISSION_REQUEST_CODE,
                *mPermissionList
            )
            return false
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String?>) {
        init()
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String?>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            showAppSettingsDialog()
        }
    }

    private fun showAppSettingsDialog() {
        AppSettingsDialog.Builder(this)
            .setTitle("权限已经被您拒绝")
            .setRationale("如果不打开权限则无法使用该功能,点击确定去打开权限")
            .setRequestCode(10001) //用于onActivityResult回调做其它对应相关的操作
            .build()
            .show()
    }
}
